package com.jwaoo.chat.activity.module.fromapp;

import com.dx.as.common.string.StringUtil;
import com.dx.as.db.SqlLiteHelper;
import com.dx.as.listener.IForChatModule;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.chat.IMessageClient;
import com.jwaoo.chat.activity.P2PMessageActivity;
import com.jwaoo.chat.data.db.ChatDatabase;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.im.SslContextBuilder;
import java.io.InputStream;
import javax.net.ssl.SSLContext;
/**
 * Created by jwaoo on 2017/8/3.
 */

public class AppInstance{
    private static IMessageClient messageClient;
    private static IForChatModule appModule;
    public static void initAppInstance(IForChatModule module){
        appModule = module;
        appModule.setiOptionFromChat(optionFromChat);
    }
    public static IForChatModule getInstance(){
        return appModule;
    }

    private static IForChatModule.IOptionFromChat optionFromChat = new IForChatModule.IOptionFromChat() {
        @Override
        public void loginChatSystem() {
            loginChat();
        }

        @Override
        public void stopChatSystem() {
            stopChatServer();
        }

        @Override
        public void closeChatDb() {
            closeChatDatabase();
        }

        @Override
        public void startChatting(int friend) {
            P2PMessageActivity.start(appModule.getConext(), friend);
        }

        @Override
        public void savePushMsg(String msgData, long time,int friend) {
            if (messageClient == null) messageClient = new IMessageClient();
            messageClient.onMessageReceived(msgData,time,friend);
        }
    };

    private static void loginChat(){
        try {
            if (StringUtil.isEmpty(appModule.getToken()) || StringUtil.isEmpty(appModule.getChatUrl())) return;
            if (messageClient != null && messageClient.isLogined() && messageClient.isConnected()) return;
            if (messageClient == null) messageClient = new IMessageClient();
            if (messageClient.getSslContext() == null ) {
                InputStream inputStream = appModule.getConext().getAssets().open("config/cert.bks");
                SslContextBuilder builder = new SslContextBuilder(inputStream);
                SSLContext context = builder.build();
                messageClient.setSslContext(context);
            }else {
                stopChatServer();
            }
            messageClient.setToken(appModule.getToken());
            final String [] strs = getChatUrl(appModule.getChatUrl());
            startChatServer(strs);
            MessageHandler.getInstace(appModule.getConext()).setIMessageClient(messageClient);
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

    private static String[] getChatUrl(String url){
        String [] str = new String[2];
        if (StringUtil.isEmpty(url)){
            return null;
        }
        int index = url.lastIndexOf(":");
        str[0] = url.substring(0,index).replace("tcp://","");
        str[1] = url.substring(index+1);
        return str;
    }

    private static void startChatServer(final String [] str){
        if (messageClient == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                messageClient.start(str[0], Integer.parseInt(str[1]));
            }
        }).start();
    }

    private static void stopChatServer(){
        if (messageClient == null) return;
//        if ( messageClient.isConnected() || messageClient.isLogined()){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    messageClient.stop();
                }
            }).start();
//        }
    }

    public static void closeChatDatabase(){
        SqlLiteHelper.getInstance(ChatHelpter.getContext()).closeDb(ChatDatabase.class,true);
    }
}